package basetest;

import org.junit.Test;
import utils.JDBCUtils;

import java.io.*;
import java.sql.*;

/**
 * @author DuJiabao
 * @create 2021-01-15 19:43
 */
public class BlobTest {
    /**
     * 写blob操作
     */
    @Test
    public void test() {
        FileInputStream fileInputStream = null;
        Connection conn = null;
        PreparedStatement ps = null;
        String sql = "insert into user_info(id, photo) values(?,?);";
        try {
            conn = JDBCUtils.getConnection();
            ps = conn.prepareStatement(sql);
            ps.setString(1, "666");
            fileInputStream = new FileInputStream("src/main/resources/config.properties");   // 用输入流的方式传入
            ps.setBlob(2, fileInputStream);  // 不能用setObject，要用setBlob
            ps.execute();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeSource(conn);
            JDBCUtils.closeSource(ps);
            JDBCUtils.closeSource(fileInputStream);
        }
    }

    /**
     * 读操作
     */
    @Test
    public void test2() {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        InputStream binaryStream = null;
        FileOutputStream fileOutputStream = null;
        String sql = "select id, photo from user_info where id=666;";
        try {
            conn = JDBCUtils.getConnection();
            ps = conn.prepareStatement(sql);
            ps.executeQuery();// 记得要执行！
            rs = ps.getResultSet();
            if (rs.next()) {
                System.out.println(rs.getInt("id"));
                Blob blob = rs.getBlob("photo");
                binaryStream = blob.getBinaryStream();   // 已二进制流的方式获取
                fileOutputStream = new FileOutputStream("src/main/resources/6666.txt"); //并将获取到流输出
                byte[] bytes = new byte[1024];
                while (binaryStream.read(bytes) != -1) {
                    fileOutputStream.write(bytes);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeSource(conn);
            JDBCUtils.closeSource(ps);
            JDBCUtils.closeSource(rs);
            JDBCUtils.closeSource(binaryStream);
            JDBCUtils.closeSource(fileOutputStream);
        }
    }
}
